package edu.pitt.cs.cs2510.project3.model;

import edu.pitt.cs.cs2510.project3.configuration.InputParameters;

public class StaticFrontEnd extends FrontEnd {

	final int NUM_WORKERS;
		
	public StaticFrontEnd(int id, InputParameters simulationParameters, Object monitor) {
		super(id, simulationParameters, monitor);
		NUM_WORKERS =  simulationParameters.getStaticFrontendCount(); 
		int workerIndex = 0;
		for (int i = 0; i < NUM_WORKERS; i++){
			this.workers.add(new WorkerServer(i, simulationParameters, this, monitor));
		}
		for (File f : files.values()) {
			f.master = true;
			this.workers.get(workerIndex).files.put(f.fileId, f);
			workerIndex = (workerIndex + 1) % NUM_WORKERS;
		}
		for (int i = 0; i < NUM_WORKERS; i++){
			this.workers.get(i).start();
		}
	}

	@Override
	protected void handleMessage(Message message) {
		super.handleMessage(message);
	}

	@Override
	protected void handleRequest(Request request) {
		super.handleRequest(request);
	}

	@Override
	protected void runAlgorithm() {
		super.runAlgorithm();
	}
	
	protected void handleReplication(Request r, String source){
		super.handleReplication(r, source);
	}
	
	protected WorkerServer getReplicationTarget(Request r, String source){
		WorkerServer target = null;
		float load = Float.MAX_VALUE;
		int storage = 0;
		for (WorkerServer w : workers){
			if(w.getUniqueIdentifier().equals(source)){
				continue;
			}
			if(w.files.isEmpty()){
				return w;
			}
			if (!w.hasFile(r.fileId) && w.remainingSpace() >= files.get(r.fileId).size && w.getLoad() <= load && w.remainingSpace() > storage){
				target = w;
				load = w.getLoad();
				storage = w.remainingSpace();
			}
		}
		if(load < super.MAX_WORKER_LOAD){
			return target;	
		}else{
			return null;
		}
	}
	
	@Override
	public boolean isDone() {
		return super.isDone();
	}
	
	public WorkerServer getWorker(int index) {
		return workers.get(index);
	}
	public int getWorkerCount() {
		return workers.size();
	}
}
